package xdu.lz.stage4_atomic.chapter5_atomicxxxArray;

import java.util.concurrent.CountDownLatch;

/**
 * Created at 2019/10/17 0017 下午 6:06
 * 通过原子的方式更新数组里的某个元素，Atomic包提供了以3类
 * AtomicIntegerArray：原子更新整型数组里的元素。
 * AtomicLongArray：原子更新长整型数组里的元素。
 * AtomicReferenceArray：原子更新引用类型数组里的元素。
 */
public class AtomicIntegerArray {

    private static int threadCount = 100;

    private static CountDownLatch countDown = new CountDownLatch(threadCount);

    private static int[] array = new int[10];

    public static void main(String[] args) throws InterruptedException {
        Thread[] threads = new Thread[threadCount];
        /**
         * 每个线程对元组进行更新100次
         */
        for (int count = 0; count < threadCount; count++) {
            threads[count] = new Thread(()->{
                for (int i = 0; i < 100; i++) {
                    for (int j = 0; j < 10; j++) {//所有元素+1
                        array[j]++;
                    }
                }
                countDown.countDown();
            });
        }
        for (int i = 0; i < threadCount; i++) {
            threads[i].start();
        }
        countDown.await();

        for (int i = 0; i < 10; i++) {
            System.out.print(array[i] + " ");
        }
    }
}
